<template>
  <FormDialog :formOption="formOption" :form="form" :rule="rule" ref="dialogRef" :reload="reload"/>
</template>

<script setup lang="ts">
import FormDialog from "~/components/common/FormDialog.vue";
import {
  useApi
} from "~/composeables";
import {FormFieldType, FormOption} from "~/models/data/form";
import InformationCategoryCache from "~/store/cmssvr/informationCategoryCache";

const props = defineProps<{
  reload: Function,
}>();

const api = useApi();

const dialogRef = ref<any>(null);

const submitFunc = (model: any) => {
  api.informationApi.update(model)
    .then(res => {
      if (res.success) {
        ElMessage.success("提交数据成功！");
        if (props.reload) {
          props.reload();
        }
        close();
      } else {
        ElMessage.error("数据提交失败,请重新尝试！");
      }
    })
    .catch(err => {
      console.error(err);
      ElMessage.error("数据提交失败");
    })
}

const formOption = ref<FormOption>({
  title: '新建信息',
  width: 480,
  labelWidth: 120,
  fieldList: [
    {
      fieldName: 'title',
      verboseName: '标题',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'subtitle',
      verboseName: '副标题',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'description',
      verboseName: '描述信息',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'externalUrl',
      verboseName: '跳转链接',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'categoryId',
      verboseName: '所属分类',
      fieldType: FormFieldType.cascader,
      selectSource: InformationCategoryCache.informationCategoryTreeSelectSource,
      isMultiSelect: false,
    },
    {
      fieldName: 'content',
      verboseName: '信息内容',
      fieldType: FormFieldType.richText,
    },
    {
      fieldName: 'thumbnail',
      verboseName: '封面图',
      fieldType: FormFieldType.upload,
      uploadAction: 'upload',
      uploadFormats: ['jpg', 'jpeg', 'png', 'webp', 'gif']
    },
  ],
  submitFunc: submitFunc,
});

const form: any = ref({
});

const rule = ref([]);

const open = (model: any) => {
  dialogRef.value.open(JSON.parse(JSON.stringify(model)));
}

const close = () => {
  dialogRef.value.close();
}

defineExpose({
  open,
  close,
  dialogRef,
})

</script>